#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rbatis;



use rocket::{Route, Catcher, Request, Data};
use rocket::http::{Status, RawStr, Method::*};
use rocket::handler::{Handler, Outcome};
use futures::executor::block_on;

mod study_1;
mod pkg;
mod conf;
mod middleware;
mod route;
mod model;

use route::api::auth;
use pkg::e::error;
use lazy_static::lazy_static;
use std::thread;
use rbatis::rbatis::Rbatis;
use rbatis::Error;


// lazy_static! {
//   // Rbatis是线程、协程安全的，运行时的方法是Send+Sync，无需担心线程竞争
//   static ref RB:Rbatis=Rbatis::new();
// }
//


fn name<'a>(req: &'a Request, data: Data) -> Outcome<'a> {
    let param = req.get_param::<&'a RawStr>(0)
        .and_then(|res| res.ok())
        .unwrap_or("unnamed".into());
    Outcome::from(req, param.as_str())
}


pub async fn link_rbatis() {
    println!("init  rbatis start");
    fast_log::init_log("requests.log", 1000, log::Level::Info, None, true);
    let rb = Rbatis::new();
    let ret = rb.link("mysql://root:123456@localhost1:3306/test").await;
    match ret{
        Ok(_) => {
            println!("connect db suc!");
        }
        Err(err) => {
            println!("{:?}", err)
        }
    }

    // custom connection option(自定义连接参数)
    // let db_cfg=DBConnectOption::from("mysql://root:123456@localhost:3306/test")?;
    // rb.link_cfg(&db_cfg,PoolOptions::new());

    // custom pool(自定义连接池)
    // let mut opt = PoolOptions::new();
    // opt.max_size = 20;
    // rb.link_opt("mysql://root:123456@localhost:3306/test", &opt).await.unwrap();
    // return rb;
}


fn rocket() -> rocket::Rocket {
    /*
    let always_forward = Route::ranked(1, Get, "/", forward);
    let hello = Route::ranked(2, Get, "/", hi);

    let echo = Route::new(Get, "/echo/<str>", echo_url);
    let name = Route::new(Get, "/<name>", name);
    let post_upload = Route::new(Post, "/", upload);
    let get_upload = Route::new(Get, "/", get_upload);

    let not_found_catcher = Catcher::new(404, not_found_handler);

*/
    println!("connect db start");

    // api
    let auth_routes = auth::routes();
    //error catcher
    let errors = error::errors();

    let name = Route::new(Get, "/<name>", name);
    rocket::ignite()
        .mount("/hi", vec![name])     //测试路由
        .mount("/auth", auth_routes)        //用户中心路由
        .register(errors)                        //错误捕捉
}


fn main() {
    study_1::a::test_entry();

    block_on(link_rbatis());


    let a = thread::spawn(|| {
        rocket().launch();
    });
    a.join();
}